package com.yoomiito.app

import android.Manifest
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Environment
import android.text.Spannable
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.text.style.StrikethroughSpan
import android.util.Log
import android.view.View
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.net.http.RequestResponse
import com.yoomiito.app.utils.AllUtils
import com.yoomiito.app.utils.DateUtils
import com.yoomiito.app.utils.DownloadUtils
import com.yoomiito.app.utils.DownloadUtils.OnDownloadListener1
import com.yoomiito.app.utils.FileUtils.createSaveFile
import com.yoomiito.app.utils.ResUtil
import com.yoomiito.app.utils.Type
import com.yoomiito.app.utils.UserInfoConfig
import com.yoomiito.app.utils.YMToast
import com.yoomiito.app.utils.wx.WXUtils
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.regex.Pattern


/**
 * 扩展函数
 */


/**
 * 是否为空  true 是  false 否
 */
fun Any.isNull(): Boolean = this == null

/**
 * 对数字进行处理  保留两位小数
 *  如 1、1.0、1.00 -> 1
 *   10000、10000.0、10000.00->1w
 *   12345、12345.0、12345.00-> 1.2w
 */
fun String.saleNum(): String {
    var addW = false
    var str = this
    val n = this.toDouble()
    if (n >= 10000){
        addW = true
        str = (n / 10000).toString().let {
            if (it.length-(it.indexOf(".")+1)>=2){
                it.substring(0, it.indexOf(".") + 3)
            }else{
                it.substring(0, it.indexOf(".") + 2)
            }

        }
    }

    str = str.removeDecimalPoint()
    return str + if (addW) "w" else ""
}

/**
 * 格式化数字 保留一位小数
 *  如 1、1.0、1.00 -> 1
 *   10000、10000.0、10000.00->1w+
 *   12345、12345.0、12345.00-> 1.2w+
 */
fun String.formatNum(): String {
    var addW = false
    var str = this
    val n = this.toDouble()
    if (n >= 10000){
        addW = true
        str = (n / 10000).toString().let { it.substring(0, it.indexOf(".") + 2) }
    }

    str = str.removeDecimalPoint()
    return str + if (addW) "w+" else ""
}

/**
 * 格式化数字 保留一位小数 不带+
 *  如 1、1.0、1.00 -> 1
 *   10000、10000.0、10000.00->1w+
 *   12345、12345.0、12345.00-> 1.2w+
 */
fun String.formatNumWithOutAdd(): String {
    var addW = false
    var str = this
    val n = this.toDouble()
    if (n >= 10000){
        addW = true
        str = (n / 10000).toString().let { it.substring(0, it.indexOf(".") + 2) }
    }

    str = str.removeDecimalPoint()
    return str + if (addW) "w" else ""
}

fun <T> RequestResponse<T>.error() {
    when (this.code) {
        401 -> {
        }
        else -> {
            YMToast.showText(this.msg)
        }
    }
}

fun String.showLog(type: String) {
    if (BuildConfig.DEBUG) {
        Log.i("YM", "[$type]：$this")
    }
}

fun View.isVisible(visible: Boolean) {
    this.visibility = if (visible) View.VISIBLE else View.GONE
}

fun Context.getColorRef(@ColorRes res: Int): Int {
    return ContextCompat.getColor(this, res)
}

fun Context.getDrawableRef(@DrawableRes res: Int): Drawable? {
    return ContextCompat.getDrawable(this, res)
}

fun String.isEmptyOr0(): Boolean = this.isNullOrEmpty() || "0" == this || "0.0" == this || "0.00" == this

fun String.removeDecimalPoint(): String = when {
    this.isNull() -> ""
    this.endsWith(".00") -> this.substring(0, this.length - 3)
    this.endsWith(".0") -> this.substring(0, this.length - 2)
    this.contains(".") && this.endsWith("0") -> this.substring(0, this.length - 1)
    else -> this
}

//商品价格样式
fun String.goodsPrice(goodsPrice:String,showUnderLine:Boolean = true,endColorResId:Int = R.color.color_balk_999999):SpannableString{
    val spannableString = SpannableString(this)
    if (goodsPrice.isEmpty())return spannableString
    spannableString.setSpan(RelativeSizeSpan(0.53f), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    spannableString.setSpan(RelativeSizeSpan(0.65f), (if (goodsPrice.contains(".")) goodsPrice.indexOf(".") else goodsPrice.length) + 1, this.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    spannableString.setSpan(ForegroundColorSpan(ResUtil.getColor(endColorResId)), goodsPrice.length + 2, this.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    if (showUnderLine) spannableString.setSpan(StrikethroughSpan(), goodsPrice.length + 2, this.length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
    return spannableString
}

fun String.goodsPrice(goodsPrice:String,showUnderLine:Boolean = true,endColorResId:Int = R.color.color_balk_999999,oldPriceSize:Float = 0.65f):SpannableString{
    val spannableString = SpannableString(this)
    spannableString.setSpan(RelativeSizeSpan(0.53f), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    spannableString.setSpan(RelativeSizeSpan(0.65f), (if (goodsPrice.contains(".")) goodsPrice.indexOf(".") else goodsPrice.length) + 1, goodsPrice.length+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    spannableString.setSpan(RelativeSizeSpan(oldPriceSize), goodsPrice.length+2, this.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    spannableString.setSpan(ForegroundColorSpan(ResUtil.getColor(endColorResId)), goodsPrice.length + 2, this.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    if (showUnderLine) spannableString.setSpan(StrikethroughSpan(), goodsPrice.length + 2, this.length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
    return spannableString
}

fun String.youmiGoodsPrice(goodsPrice:String,youmiTextSize:Float=0.55f):SpannableString{
    val spannableString = SpannableString(this)
    spannableString.setSpan(RelativeSizeSpan(0.53f), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
//    if (goodsPrice.contains("."))
//        spannableString.setSpan(RelativeSizeSpan(0.65f), goodsPrice.indexOf(".") + 1, this.indexOf(" "), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
//    spannableString.setSpan(RelativeSizeSpan(0.65f), this.indexOf(" "), this.indexOf(" ")+4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
//    spannableString.setSpan(RelativeSizeSpan(0.65f), this.indexOf(" ")+4, this.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    spannableString.setSpan(RelativeSizeSpan(0.65f),  if (goodsPrice.contains(".")) goodsPrice.indexOf(".") + 1 else this.indexOf(" "), this.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    spannableString.setSpan(ForegroundColorSpan(ResUtil.getColor(R.color.color_balk_999999)), goodsPrice.length + 2, this.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    return spannableString
}

/**
 * 过滤
 * @return true->原值    false->null
 */
fun String.strFilter(str:(String)->Boolean):String? = if (str(this)) this else null

/**
 * 吐司
 * null empty blank 不吐司   其他正常吐司
 */
fun String.showToast(){
    this.strFilter { !(it.isNullOrEmpty()||it.isNullOrBlank()) }?.let{ YMToast.showCenterToast(it) }
}

fun View.goodsShowCoupon(couponValue:String,type:Int){
    when(type){
        Type.GoodsType.TaoBao->{
            this.visibility = if (couponValue.isEmptyOr0()) View.GONE else View.VISIBLE
        }
        Type.GoodsType.AgentMall,Type.GoodsType.YouPin->{
           this.visibility =  if (!App.mAppConfig.isLogin || couponValue.isEmptyOr0()) View.GONE else View.VISIBLE
        }
        Type.GoodsType.BaoPin->{
            this.visibility = if (!App.mAppConfig.isLogin || UserInfoConfig.getRoleId()== Type.LevelType.VIP_0 || couponValue.isEmptyOr0()) View.GONE else View.VISIBLE
        }
//        Type.GoodsType.AgentMall->{
//
//        }
        Type.GoodsType.Gift->{
            this.visibility = if (!App.mAppConfig.isLogin || UserInfoConfig.getRoleId()<= Type.LevelType.VIP_7 || couponValue.isEmptyOr0()) View.GONE else View.VISIBLE
        }
    }
}

fun View.goodsShowYoumi(youmiValue:String,type:Int){
    when(type){
        Type.GoodsType.TaoBao->{

        }
        Type.GoodsType.AgentMall,Type.GoodsType.YouPin->{
            this.visibility =  if (youmiValue.isEmptyOr0()) View.GONE else View.VISIBLE
        }
        Type.GoodsType.BaoPin->{
            this.visibility = if (youmiValue.isEmptyOr0()) View.GONE else View.VISIBLE
        }
//        Type.GoodsType.AgentMall->{
//
//        }
        Type.GoodsType.Gift->{
            this.visibility = if (youmiValue.isEmptyOr0()) View.GONE else View.VISIBLE

        }
    }
}

/**
 * 获取url中某个参数的值
 */
fun String.paramFromUrl(key:String="id"):String{
    val p = Pattern.compile("(?<=(\\?|&)$key=).*?(?=&|$)")
    val matcher = p.matcher(this)
    if (matcher.find()) {
        return matcher.group()
    }
    return ""
}

fun String.copyClipboard(context: Context,toast:String="文字复制成功"){
    if (!this.isNullOrEmpty()){
        val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        clipboard.setPrimaryClip(ClipData.newPlainText("Label", this))
        toast.showToast()
    }
}

fun String.saveVideo(activity:BaseActivity<*>){
    AllUtils.requestPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE)
            .subscribe { aBoolean ->
                if (aBoolean!!)
                    activity.showLoading()
                val appDir = File(activity.externalCacheDir, "video")
                if (!appDir.exists()) {
                    appDir.mkdir()
                }
                DownloadUtils.get().download(
                    this,
                    appDir.absolutePath,DateUtils.current() + ".mp4",
                    object : OnDownloadListener1 {
                        override fun onDownloadSuccess(file: File?) {
                            activity.dismissLoading()
                            createSaveFile(
                                activity,
                                file,
                                0,
                                DateUtils.current() + ".mp4",
                                "shareVideo"
                            )

                        }
                        override fun onDownloading(progress: Int) {
//
                        }

                        override fun onDownloadFailed(e: Exception?) {}
                    })

                //下载视频
//                DownloadUtils.download(path1, this) {
//                    activity.dismissLoading()
//                    createSaveFile(
//                        activity,
//                        it,
//                        0,
//                        DateUtils.current() + ".mp4",
//                        "shareVideo"
//                    )

                    "保存成功".showToast()
            }
}

fun String.saveVideoAndOpenWx(activity:BaseActivity<*>){
    AllUtils.requestPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE)
            .subscribe { aBoolean ->
                if (aBoolean!!)
                    activity.showLoading()
                val path = Environment.getExternalStorageDirectory().path + "/DCIM/video_" + DateUtils.current() + ".mp4"
                //下载视频
                DownloadUtils.download(path, this) {
                    activity.dismissLoading()
                    WXUtils.openWX(activity)
                    val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
                    val contentUri = Uri.fromFile(it)
                    mediaScanIntent.data = contentUri
                    activity.sendBroadcast(mediaScanIntent)
                }
            }
}

/**
 * 数字小于1w时，显示小数点后两位，如9281.18；
 * 数字大于等于1w且小于10w时，不显示小数点后两位，如12983；
 * 数字大于10w时，显示w，如11.22w
 */
fun String.formatNum1():String{
        return when{
            this.compare("100000")->{
                 "${(this.toDouble()/10000).toString().saveDecimal2().removeTrim()}w"
            }
            this.compare("10000")->{
                //大于等于1w
                val index = this.indexOf(".")
                if (index>0){
                    this.substring(0,index)
                }else{
                    this
                }
            }
            else->{
                //小于1w
                this.removeTrim()
            }
        }
}

/**
 * 数字小于10w时，显示完整数字，如99827；数字大于等于10w时，显示w，如10.1w
 */
fun String.formatNum2():String{
    val value =  when{
        this.compare("100000")->{
            //大于10w
            "${(this.toDouble()/10000).toString().saveDecimal1().removeTrim()}w"
        }
        else->{
            //小于10w
           this
        }
    }
    return value
}

fun Double.distanceFormat():String{
    return when{
        this > 1000.0->{
            //大于1k
            "${(this/1000).toString().saveDecimal2().removeTrim()}km"
        }
        else->{
            //小于1k
            "${this.toString().saveDecimal2().removeTrim()}m"
        }
    }
}

fun Float.distanceFormat():String{
    return when{
        this > 1000->{
            //大于1k
            "${(this/1000).toString().saveDecimal2().removeTrim()}km"
        }
        else->{
            //小于1k
            "${this.toString().saveDecimal2().removeTrim()}m"
        }
    }
}

/**
 * 大于等于 true
 * 小于 false
 */
fun String.compare(value:String):Boolean = this.toDouble()>=value.toDouble()

fun String.removeTrim():String{
    var str = this
    if(str.indexOf(".") > 0){
        str = str.replace(Regex("0+?$"), "")//去掉多余的0
        str = str.replace(Regex("[.]$"), "")//如最后一位是.则去掉
    }
    return str
}

/**
 * 保留2位小数
 */
fun String.saveDecimal2():String{
    return if (this.contains(".")){
        val index = this.indexOf(".")
        if (this.length-index>=3){
            this.substring(0,index+3)
        }else{
            this
        }
    }else{
        this
    }
}

/**
 * 保留1位小数
 */
fun String.saveDecimal1():String{
    return if (this.contains(".")){
        val index = this.indexOf(".")
        if (this.length-index>=2){
            this.substring(0,index+2)
        }else{
            this
        }
    }else{
        this
    }
}

fun String.printJson(tag: String) {
    val LINE_SEPARATOR = System.getProperty("line.separator")
    val top =
            "╔═══════════════════════════════════════════════════════════════════════════════════════"
    val bottom =
            "╚═══════════════════════════════════════════════════════════════════════════════════════"
    val str = when {
        this.startsWith("{") -> {
            val jsonObject = JSONObject(this)
            jsonObject.toString(4)
        }
        this.startsWith("[") -> {
            val jsonArray = JSONArray(this)
            jsonArray.toString(4)
        }
        else -> {
            this
        }
    }
    Log.d(tag, top)
    val lines = str.split(LINE_SEPARATOR!!)
    lines.forEach {
        Log.d(tag, "║ $it" )
    }
    Log.d(tag, bottom)
}
